import { useEffect, useRef, useState } from "react";

type DotsWaitingOptions = {
    dotChar?: string; // 点的字符，默认是'.'
    interval?: number; // 间隔时间，默认500ms
    enabled?: boolean; // 是否启用，默认false
}

/**
 * dots等待效果hook
 * @param options 配置选项
 * @returns [dots, resetDots]
 */
export default function useDotsWaiting(options : DotsWaitingOptions = {}): string {
  const {dotChar = '.', interval = 500 , enabled = false} = options;
  const [dots, setDots] = useState("");
  const dotsRef = useRef<NodeJS.Timeout | null>(null);

  useEffect(() => {
    if (!enabled) return;

    dotsRef.current = setInterval(() => {
      setDots((prev) => (prev.length < 3 ? prev + dotChar : ""));
    }, interval);

    return () => {
      if (dotsRef.current) {
        clearInterval(dotsRef.current);
        dotsRef.current = null;
      }
      setDots("");
    };
  }, [interval, enabled]);

  return dots;
}